package de.justphil.tcg.tcgserver.rest;


import static de.justphil.tcg.tcgserver.commons.logging.TCGLogging.*;

import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.api.json.JSONConfiguration;

import de.justphil.tcg.tcgserver.commons.config.Config;
import de.justphil.tcg.tcgserver.commons.grid.Grid;
import de.justphil.tcg.tcgserver.rest.db.MockDataCreator;
import de.justphil.tcg.tcgserver.rest.services.GameService;
import de.justphil.tcg.tcgserver.commons.management.Application;

import javax.ws.rs.core.UriBuilder;

import org.glassfish.grizzly.http.server.HttpServer;
import org.slf4j.Logger;

import java.io.IOException;
import java.net.URI;


public class TCGRestServer {
	private static final Logger log = restLogger(TCGRestServer.class);
	
	
    private static int getPort(int defaultPort) {
        String port = System.getProperty("jersey.test.port");
        if (null != port) {
            try {
                return Integer.parseInt(port);
            } catch (NumberFormatException e) {
            }
        }
        return defaultPort;
    } 
    
    private static URI getBaseURI() {
        return UriBuilder.fromUri("http://0.0.0.0/").port(getPort(Config.REST_SERVER_PORT)).build();
    }

    public static final URI BASE_URI = getBaseURI();

    protected static HttpServer startServer() throws IOException {
        log.info("Starting Grizzly HTTP engine...");
        
        ResourceConfig rc = new PackagesResourceConfig(
        		"de.justphil.tcg.tcgserver.rest.resources",
        		"com.yammer.metrics.jersey"
        );
        
        rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        HttpServer http = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
        return http;
    }
    
    public static void main(String[] args) throws IOException {
    	//ConsoleReporter.enable(3, TimeUnit.SECONDS);
    	
    	
    	//ImagesDirectory.init();
    	db();
    	Grid.initRestServerGrid();
    	Application.getDataManager().init();
    	
    	
        HttpServer httpServer = startServer();
        System.out.println(String.format("TCG REST Server started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
        
        GameService.getInstance().start();
        
        System.in.read();
        httpServer.stop();
    }
    
    public static void db() {
    	MockDataCreator mdc = new MockDataCreator(Application.getEntityManagerFactory());
    	mdc.insertMockData();
    	
    	/*
    	
    	EntityManagerFactory factory = Persistence.createEntityManagerFactory("tcg");
		EntityManager em = factory.createEntityManager();
		
		TypedQuery<User> q = em.createQuery("SELECT u FROM User u", User.class);
		List<User> userList = q.getResultList();
		for (User u : userList) {
			System.out.println(u);
		}
		System.out.println("Size: " + userList.size());

		
		em.getTransaction().begin();
		User user = new User("123", "phil", "123asd");
		
		em.persist(user);
		em.getTransaction().commit();

		em.close();
		
		*/
    }
}
